package com.example.app;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

import com.example.app.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.btn1.setOnClickListener(v->{
            wtiteSharedPreference();
        });
        binding.btn2.setOnClickListener(v->{
            readSharedPreference();
        });

    }

    private void wtiteSharedPreference(){
        String fileName = "";
        SharedPreferences.Editor editor = getSharedPreferences(fileName, Context.MODE_PRIVATE).edit();
        editor.putString("name", String.valueOf(binding.et1.getText()));
        editor.putString("age", String.valueOf(binding.et2.getText()));
        editor.apply();
        Toast.makeText(this,"成功",Toast.LENGTH_SHORT).show();
    }

    private void readSharedPreference(){
        String fileName = "";
        SharedPreferences editor = getSharedPreferences(fileName, Context.MODE_PRIVATE);
        String name = editor.getString("name","");
        String age = editor.getString("age","");
        binding.tv1.setText(name);
        binding.tv2.setText(age);
        Toast.makeText(this,"成功",Toast.LENGTH_SHORT).show();
    }
}